package us.mooresr.geartrack.server.handler;

import java.util.Date;

import us.mooresr.geartrack.server.DAO;
import us.mooresr.geartrack.shared.action.CheckOutItemAction;
import us.mooresr.geartrack.shared.action.CheckOutItemResult;
import us.mooresr.geartrack.shared.model.Item;
import us.mooresr.geartrack.shared.model.Loan;

import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class CheckOutItemActionHandler 
	implements ActionHandler<CheckOutItemAction, CheckOutItemResult> {

	@Override
	public CheckOutItemResult execute(CheckOutItemAction action,
			ExecutionContext arg1) throws ActionException {
		Long itemId = action.getItemId();
		Long personId = action.getPersonId();
		
		DAO dao = new DAO();
		
		Loan loan = new Loan();
		
		loan.setBorrowerId(personId);
		loan.setItemId(itemId);
		loan.setCheckInDate(null);
		loan.setCheckOutDate(new Date());
		
		dao.ofy().put(loan);
		
		Item returnItem = dao.ofy().get(Item.class, itemId);
		
		CheckOutItemResult result  = new CheckOutItemResult(returnItem);
		
		return result;
		
	}

	@Override
	public Class<CheckOutItemAction> getActionType() {
		return CheckOutItemAction.class;
	}

	@Override
	public void undo(CheckOutItemAction arg0, CheckOutItemResult arg1,
			ExecutionContext arg2) throws ActionException {
		// TODO Auto-generated method stub
		
	}

}
